import model.Book;
import model.BookDB;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

@WebServlet("/listBooks")
public class ListBookServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应编码为UTF-8，避免中文乱码
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        out.println("<html><head><title>图书列表</title><style>" +
                "body { font-family: Arial, sans-serif; }" +
                "table { border-collapse: collapse; width: 100%; }" +
                "th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }" +
                "th { background-color: #f2f2f2; }" +
                "</style></head><body>");

        out.println("<h2>图书列表</h2>");
        out.println("<table><tr><th>ID</th><th>书名</th><th>价格</th><th>操作</th></tr>");

        List<Book> books = BookDB.getAllBooks();
        for (Book book : books) {
            out.println("<tr><td>" + book.getId() + "</td><td>" + book.getName() + "</td><td>" + book.getPrice() + "</td><td><button onclick='addToCart(\"" + book.getId() + "\")'>加入购物车</button></td></tr>");
        }

        out.println("</table>");

        out.println("<script>" +
                "function addToCart(bookId) {" +
                "    fetch('/purchase?bookId=' + bookId, { method: 'POST' }) " +
                "     .then(response => response.json())" +
                "     .then(data => {" +
                "            if (data.success) {" +
                "                alert('已加入购物车！');" +
                "            } else {" +
                "                alert('加入购物车失败！');" +
                "            }" +
                "        });" +
                "}" +
                "</script>");

        out.println("</body></html>");
    }
}